/*
 * Copyright (C) 2020 The zfoo Authors
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

package org.ricks.ioc.event;

import org.ricks.ioc.HotfixManager;
import org.ricks.ioc.event.anno.Bus;
import org.ricks.ioc.utils.Logger;
import org.ricks.ioc.utils.ReflectUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 动态代理被EventReceiver注解标注的方法，为了避免反射最终会用javassist字节码增强的方法去代理EventReceiverDefinition
 *
 * @author godotg
 */
public class EventReceiverDefinition implements IEventReceiver {

    // 观察者的bean
    private final Object bean;

    // 被EventReceiver注解标注的方法
    private final Method method;

    // 事件接收方式
    private final Bus bus;

    // 接收的参数Class
    private final Class<? extends IEvent> eventClazz;

    public EventReceiverDefinition(Object bean, Method method, Bus bus, Class<? extends IEvent> eventClazz) {
        this.bean = bean;
        this.method = method;
        this.bus = bus;
        this.eventClazz = eventClazz;
        this.method.setAccessible(true);
    }

    @Override
    public Bus bus() {
        return bus;
    }

    @Override
    public void invoke(IEvent event) {
        ReflectUtils.invokeMethod(bean, method, event);
    }

//    public Object getBean() {
//        return bean;
//    }

    public Method getMethod() {
        return method;
    }

    public Bus getBus() {
        return bus;
    }

    public Class<? extends IEvent> getEventClazz() {
        return eventClazz;
    }

    /**
     * 获取实际使用的类（优先使用热更后的类）
     */
    private Class<?> getActualClass() {
        Class<?> beanClass = bean.getClass();
        Class<?> hotfixClass = HotfixManager.getHotfixClass(beanClass.getName());
        return hotfixClass != null ? hotfixClass : beanClass;
    }


    /**
     * 获取实际使用的Bean实例（优先使用热更后的类实例）
     */
    public Object getBean() {
        Class<?> beanClass = bean.getClass();
        Class<?> actualClass = getActualClass();
        if (actualClass != beanClass) {
            // 需要创建热更后的类实例
            try {
                Object hotfixBean = actualClass.getConstructor().newInstance();
                // 复制字段值
                copyFieldValues(bean, hotfixBean);
                return hotfixBean;
            } catch (Exception e) {
                Logger.error("创建热更实例失败", e);
                return bean;
            }
        }
        return bean;
    }

    /**
     * 复制字段值从旧实例到新实例
     */
    private void copyFieldValues(Object source, Object target) {
        Class<?> sourceClass = source.getClass();
        Class<?> targetClass = target.getClass();

        while (sourceClass != null && targetClass != null) {
            for (Field sourceField : sourceClass.getDeclaredFields()) {
                try {
                    Field targetField = targetClass.getDeclaredField(sourceField.getName());
                    if (targetField.getType().isAssignableFrom(sourceField.getType())) {
                        sourceField.setAccessible(true);
                        targetField.setAccessible(true);
                        targetField.set(target, sourceField.get(source));
                    }
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    // 忽略不存在的字段或访问异常
                }
            }
            sourceClass = sourceClass.getSuperclass();
            targetClass = targetClass.getSuperclass();
        }
    }



}
